package com.zjj.distributed.zk.curator;

import lombok.extern.slf4j.Slf4j;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.zookeeper.data.Stat;

/**
 * @author zhanglei.zjj
 * @description curator操作公共行为抽象
 * @date 2023/6/20 20:54
 */
@Slf4j
public class CuratorBaseOperations {
    public final static String CLUSTER_CONNECT_STR = "192.168.200.129:2181";
    protected static CuratorFramework curatorFramework = CuratorFrameworkFactory.builder()
            .connectString(CLUSTER_CONNECT_STR)
            .sessionTimeoutMs(4000)
            .retryPolicy(new ExponentialBackoffRetry(1000, 3)).
            namespace("").build();

    static {
        //启动客户端
        curatorFramework.start();
    }

    public void createIfNeed(String nodeCache, String data) {
        try {
            Stat stat = curatorFramework.checkExists().forPath(nodeCache);
            if (stat == null) {
                curatorFramework.create().forPath(nodeCache, data.getBytes());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void printNodeData(String node) throws Exception {
        byte[] bytes = curatorFramework.getData().forPath(node);
        log.info("data: {}", new String(bytes));
    }
}
